Security News
pnpm 10.0.0 Blocks Lifecycle Scripts by Default
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
The nanoid npm package is a small, secure, URL-friendly, unique string ID generator for JavaScript applications. It is designed to be fast and efficient, producing random or custom ID strings suitable for a variety of applications, including database keys, session identifiers, and more.
Simple ID Generation
Generate a unique, URL-friendly ID. The default ID length is 21 characters, which provides a good balance of speed and uniqueness.
const { nanoid } = require('nanoid');
console.log(nanoid()); // Example output: 'V1StGXR8_Z5jdHi6B-myT'
Custom Length ID Generation
Generate a unique ID with a custom length. This allows for shorter or longer IDs depending on the level of uniqueness required.
const { nanoid } = require('nanoid');
console.log(nanoid(10)); // Example output: 'IRFa-VaY2b'
Non-secure ID Generation
Generate a non-secure ID with a custom alphabet and length. This is useful for cases where unique IDs are needed without the cryptographic strength.
const { customAlphabet } = require('nanoid');
const nanoid = customAlphabet('1234567890abcdef', 10);
console.log(nanoid()); // Example output: '4f90d13a42'
Custom Alphabet ID Generation
Generate a unique ID using a custom alphabet. This is useful when you need to avoid certain characters or use a specific set of characters for IDs.
const { customAlphabet } = require('nanoid');
const alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const nanoid = customAlphabet(alphabet, 10);
console.log(nanoid()); // Example output: '4f90d13a42'
The uuid package can generate RFC-compliant UUIDs. It offers different versions of UUIDs, such as v1 (timestamp-based), v4 (random), and others. Compared to nanoid, uuid provides more standardized and structured IDs, but they are not as compact as nanoid's IDs.
Shortid is another package for generating short non-sequential url-friendly unique ids. However, it is no longer recommended for use as it has been deprecated in favor of nanoid, which is more secure and maintains a smaller size.
Uniqid is a package that generates unique IDs based on the current time and an optional prefix or suffix. It is less feature-rich compared to nanoid and does not provide the same level of customization or security.
English | Русский | 简体中文 | Bahasa Indonesia
A tiny, secure, URL-friendly, unique string ID generator for JavaScript.
“An amazing level of senseless perfectionism, which is simply impossible not to respect.”
A-Za-z0-9_-
).
So ID size was reduced from 36 to 21 symbols.import { nanoid } from 'nanoid'
model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"
Supports modern browsers, IE with Babel, Node.js and React Native.
Nano ID is quite comparable to UUID v4 (random-based). It has a similar number of random bits in the ID (126 in Nano ID and 122 in UUID), so it has a similar collision probability:
For there to be a one in a billion chance of duplication, 103 trillion version 4 IDs must be generated.
There are three main differences between Nano ID and UUID v4:
uuid/v4
package:
130 bytes instead of 483.$ node ./test/benchmark.js
crypto.randomUUID 25,603,857 ops/sec
@napi-rs/uuid 9,973,819 ops/sec
uid/secure 8,234,798 ops/sec
@lukeed/uuid 7,464,706 ops/sec
nanoid 5,616,592 ops/sec
customAlphabet 3,115,207 ops/sec
uuid v4 1,535,753 ops/sec
secure-random-string 388,226 ops/sec
uid-safe.sync 363,489 ops/sec
cuid 187,343 ops/sec
shortid 45,758 ops/sec
Async:
nanoid/async 96,094 ops/sec
async customAlphabet 97,184 ops/sec
async secure-random-string 92,794 ops/sec
uid-safe 90,684 ops/sec
Non-secure:
uid 67,376,692 ops/sec
nanoid/non-secure 2,849,639 ops/sec
rndm 2,674,806 ops/sec
Test configuration: ThinkPad X1 Carbon Gen 9, Fedora 34, Node.js 16.10.
See a good article about random generators theory: Secure random values (in Node.js)
Unpredictability. Instead of using the unsafe Math.random()
, Nano ID
uses the crypto
module in Node.js and the Web Crypto API in browsers.
These modules use unpredictable hardware random generator.
Uniformity. random % alphabet
is a popular mistake to make when coding
an ID generator. The distribution will not be even; there will be a lower
chance for some symbols to appear compared to others. So, it will reduce
the number of tries when brute-forcing. Nano ID uses a better algorithm
and is tested for uniformity.
Well-documented: all Nano ID hacks are documented. See comments in the source.
Vulnerabilities: to report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.
npm install --save nanoid
For quick hacks, you can load Nano ID from CDN. Though, it is not recommended to be used in production because of the lower loading performance.
import { nanoid } from 'https://cdn.jsdelivr.net/npm/nanoid/nanoid.js'
Nano ID provides ES modules. You do not need to do anything to use Nano ID as ESM in webpack, Rollup, Parcel, or Node.js.
import { nanoid } from 'nanoid'
In Node.js you can use CommonJS import:
const { nanoid } = require('nanoid')
Nano ID has 3 APIs: normal (blocking), asynchronous, and non-secure.
By default, Nano ID uses URL-friendly symbols (A-Za-z0-9_-
) and returns an ID
with 21 characters (to have a collision probability similar to UUID v4).
The safe and easiest way to use Nano ID.
In rare cases could block CPU from other work while noise collection for hardware random generator.
import { nanoid } from 'nanoid'
model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"
If you want to reduce the ID size (and increase collisions probability), you can pass the size as an argument.
nanoid(10) //=> "IRFa-VaY2b"
Don’t forget to check the safety of your ID size in our ID collision probability calculator.
You can also use a custom alphabet or a random generator.
To generate hardware random bytes, CPU collects electromagnetic noise. For most cases, entropy will be already collected.
In the synchronous API during the noise collection, the CPU is busy and cannot do anything useful (for instance, process another HTTP request).
Using the asynchronous API of Nano ID, another code can run during the entropy collection.
import { nanoid } from 'nanoid/async'
async function createUser () {
user.id = await nanoid()
}
Read more about entropy collection in crypto.randomBytes
docs.
Unfortunately, you will lose Web Crypto API advantages in a browser
if you use the asynchronous API. So, currently, in the browser, you are limited
with either security (nanoid
), asynchronous behavior (nanoid/async
),
or non-secure behavior (nanoid/non-secure
) that will be explained
in the next part of the documentation.
By default, Nano ID uses hardware random bytes generation for security and low collision probability. If you are not so concerned with security, you can use the faster non-secure generator.
import { nanoid } from 'nanoid/non-secure'
const id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"
customAlphabet
allows you to create nanoid
with your own alphabet
and ID size.
import { customAlphabet } from 'nanoid'
const nanoid = customAlphabet('1234567890abcdef', 10)
model.id = nanoid() //=> "4f90d13a42"
import { customAlphabet } from 'nanoid/async'
const nanoid = customAlphabet('1234567890abcdef', 10)
async function createUser () {
user.id = await nanoid()
}
import { customAlphabet } from 'nanoid/non-secure'
const nanoid = customAlphabet('1234567890abcdef', 10)
user.id = nanoid()
Check the safety of your custom alphabet and ID size in our
ID collision probability calculator. For more alphabets, check out the options
in nanoid-dictionary
.
Alphabet must contain 256 symbols or less. Otherwise, the security of the internal generator algorithm is not guaranteed.
In addition to setting a default size, you can change the ID size when calling the function:
import { customAlphabet } from 'nanoid'
const nanoid = customAlphabet('1234567890abcdef', 10)
model.id = nanoid(5) //=> "f01a2"
customRandom
allows you to create a nanoid
and replace alphabet
and the default random bytes generator.
In this example, a seed-based generator is used:
import { customRandom } from 'nanoid'
const rng = seedrandom(seed)
const nanoid = customRandom('abcdef', 10, size => {
return (new Uint8Array(size)).map(() => 256 * rng())
})
nanoid() //=> "fbaefaadeb"
random
callback must accept the array size and return an array
with random numbers.
If you want to use the same URL-friendly symbols with customRandom
,
you can get the default alphabet using the urlAlphabet
.
const { customRandom, urlAlphabet } = require('nanoid')
const nanoid = customRandom(urlAlphabet, 10, random)
Asynchronous and non-secure APIs are not available for customRandom
.
Note, that between Nano ID versions we may change random generator call sequence. If you are using seed-based generators, we do not guarantee the same result.
If you support IE, you need to transpile node_modules
by Babel
and add crypto
alias. Moreover, UInt8Array
in IE actually
is not an array and to cope with it, you have to convert it to an array
manually:
// polyfills.js
if (!window.crypto && window.msCrypto) {
window.crypto = window.msCrypto
const getRandomValuesDef = window.crypto.getRandomValues
window.crypto.getRandomValues = function (array) {
const values = getRandomValuesDef.call(window.crypto, array)
const result = []
for (let i = 0; i < array.length; i++) {
result[i] = values[i];
}
return result
};
}
import './polyfills.js'
import { nanoid } from 'nanoid'
There’s no correct way to use Nano ID for React key
prop
since it should be consistent among renders.
function Todos({todos}) {
return (
<ul>
{todos.map(todo => (
<li key={nanoid()}> /* DON’T DO IT */
{todo.text}
</li>
))}
</ul>
)
}
You should rather try to reach for stable ID inside your list item.
const todoItems = todos.map((todo) =>
<li key={todo.id}>
{todo.text}
</li>
)
In case you don’t have stable IDs you'd rather use index as key
instead of nanoid()
:
const todoItems = todos.map((text, index) =>
<li key={index}> /* Still not recommended but preferred over nanoid().
Only do this if items have no stable IDs. */
{text}
</li>
)
React Native does not have built-in random generator. The following polyfill
works for plain React Native and Expo starting with 39.x
.
react-native-get-random-values
docs and install it.import 'react-native-get-random-values'
import { nanoid } from 'nanoid'
For Rollup you will need @rollup/plugin-node-resolve
to bundle browser version
of this library.:
plugins: [
nodeResolve({
browser: true
})
]
In PouchDB and CouchDB, IDs can’t start with an underscore _
.
A prefix is required to prevent this issue, as Nano ID might use a _
at the start of the ID by default.
Override the default ID with the following option:
db.put({
_id: 'id' + nanoid(),
…
})
const mySchema = new Schema({
_id: {
type: String,
default: () => nanoid()
}
})
Web Workers do not have access to a secure random generator.
Security is important in IDs when IDs should be unpredictable. For instance, in "access by URL" link generation. If you do not need unpredictable IDs, but you need to use Web Workers, you can use the non‑secure ID generator.
import { nanoid } from 'nanoid/non-secure'
nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"
Note: non-secure IDs are more prone to collision attacks.
You can get unique ID in terminal by calling npx nanoid
. You need only
Node.js in the system. You do not need Nano ID to be installed anywhere.
$ npx nanoid
npx: installed 1 in 0.63s
LZfXLFzPPR4NNrgjlWDxn
Size of generated ID can be specified with --size
(or -s
) option:
$ npx nanoid --size 10
L3til0JS4z
Custom alphabet can be specified with --alphabet
(or -a
) option
(note that in this case --size
is required):
$ npx nanoid --alphabet abc --size 15
bccbcabaabaccab
Nano ID was ported to many languages. You can use these ports to have the same ID generator on the client and server side.
For other environments, CLI is available to generate IDs from a command line.
nanoid-dictionary
with popular alphabets to use with customAlphabet
.nanoid-good
to be sure that your ID doesn’t contain any obscene words.FAQs
A tiny (118 bytes), secure URL-friendly unique string ID generator
We found that nanoid demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
Product
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
Research
Security News
Socket researchers have discovered multiple malicious npm packages targeting Solana private keys, abusing Gmail to exfiltrate the data and drain Solana wallets.